/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import estg.dae.projecto.bank.OperationType;
import estg.dae.projecto.bank.controllers.BankSessionLocal;
import estg.dae.projecto.bank.model.Account;
import estg.dae.projecto.bank.model.AccountMovement;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Marco
 */
public class TransfersController extends HttpServlet {
    private static String VIEWS_PATH = "/WEB-INF/views/";
    @EJB
    private BankSessionLocal controller;


    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        //String actionStr = request.getParameter("action");
        String jspView = "TransferPage.jsp";
        request.setAttribute("title", "Transferências Bancárias");
        request.setAttribute("contextPath", request.getContextPath());

        jspView = doTransfer(request, response);

        request.getRequestDispatcher(VIEWS_PATH + jspView).include(request, response);
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private String doTransfer(HttpServletRequest request, HttpServletResponse response) {
        try
        {
            OperationType operationType = OperationType.valueOf(request.getParameter("operationType"));
            
            if (operationType == OperationType.Withdraw) {
                return doWithdraw(request, response);
            }
            else if (operationType == OperationType.Transfer) {
                return doElectronicTransfer(request, response);
            }
            else if (operationType == OperationType.MoneyDeposit) {
                return doMoneyDeposit(request, response);
            }
            else if (operationType == OperationType.CheckDeposit) {
                return doCheckDeposit(request, response);
            }
            else
                throw new Exception();
        }
        catch (NullPointerException error) {
            return "TransferPage.jsp";
        }
        catch (UnsupportedOperationException error) {
        }
        catch(Exception error)
        {
            request.setAttribute("operationType", request.getParameter("operationType"));
            request.setAttribute("originAccount", request.getParameter("originAccount"));
            request.setAttribute("destinAccount", request.getParameter("destinAccount"));
            request.setAttribute("value", request.getParameter("value"));

            request.setAttribute("formError", "Operação inválida.");
        }
        return "TransferSuccessPage.jsp";
    }

    private String doWithdraw(HttpServletRequest request, HttpServletResponse response) {
        try
        {
            String originAccountRef = request.getParameter("originAccount");

            double value = Double.parseDouble(request.getParameter("value"));

            AccountMovement mov = controller.doWithdraw(originAccountRef, value);

            request.setAttribute("client", mov.getAccount().getClient());
            request.setAttribute("account", mov.getAccount());
            request.setAttribute("movement", mov);
            return "TransferSuccessPage.jsp";
        }
        catch(NumberFormatException error)
        {
            request.setAttribute("formError", "Valor inválido.");
        }
        catch(Exception error)
        {
            request.setAttribute("formError", error.getMessage());
        }
        return "TransferPage.jsp";
    }

    private String doElectronicTransfer(HttpServletRequest request, HttpServletResponse response) {
        try
        {
            String destinAccountRef = request.getParameter("destinAccount");
            String originAccountRef = request.getParameter("originAccount");
            double value = Double.parseDouble(request.getParameter("value"));

            AccountMovement mov = controller.doTransfer(originAccountRef, destinAccountRef, value);

            request.setAttribute("client", mov.getAccount().getClient());
            request.setAttribute("account", mov.getAccount());
            request.setAttribute("movement", mov);
            return "TransferSuccessPage.jsp";
        }
        catch(NumberFormatException error)
        {
            request.setAttribute("formError", "Valor inválido.");
        }
        catch(Exception error)
        {
            request.setAttribute("formError", error.getMessage());
        }
        return "TransferPage.jsp";
    }

    private String doMoneyDeposit(HttpServletRequest request, HttpServletResponse response) {
        try
        {
            String destinAccountRef = request.getParameter("destinAccount");

            double value = Double.parseDouble(request.getParameter("value"));

            AccountMovement mov = controller.doMoneyDeposit(destinAccountRef, value);

            request.setAttribute("client", mov.getAccount().getClient());
            request.setAttribute("account", mov.getAccount());
            request.setAttribute("movement", mov);
            return "TransferSuccessPage.jsp";
        }
        catch(NumberFormatException error)
        {
            request.setAttribute("formError", "Valor inválido.");
        }
        catch(Exception error)
        {
            request.setAttribute("formError", error.getMessage());
        }
        return "TransferPage.jsp";
    }

    private String doCheckDeposit(HttpServletRequest request, HttpServletResponse response) {
                try
        {
            String destinAccountRef = request.getParameter("destinAccount");
            String originAccountRef = request.getParameter("originAccount");
            double value = Double.parseDouble(request.getParameter("value"));

            AccountMovement mov = controller.doCheckDeposit(originAccountRef, destinAccountRef, value);

            request.setAttribute("client", mov.getAccount().getClient());
            request.setAttribute("account", mov.getAccount());
            request.setAttribute("movement", mov);
            return "TransferSuccessPage.jsp";
        }
        catch(NumberFormatException error)
        {
            request.setAttribute("formError", "Valor inválido.");
        }
        catch(Exception error)
        {
            request.setAttribute("formError", error.getMessage());
        }
        return "TransferPage.jsp";
    }
}
